package com.fosu.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fosu.service.Util.GetUserByTokenUtil;
import com.fosu.common.ResponseResult;
import com.fosu.dao.*;
import com.fosu.domain.*;
import com.fosu.service.PublishService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


/**
 * @author zqa
 * @version 1.0
 * @date 2020/10/19 16:58
 */
@Service
@Transactional
public class PublishServiceImpl implements PublishService {

    @Autowired
    private CategoriesDao categoriesDao;
    @Autowired
    private CampusDao campusDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private ProductAndCampusDao productAndCampusDao;
    @Autowired
    private ProductAndCategoriesDao productAndCategoriesDao;
    @Autowired
    private ProductImgDao productImgDao;
    @Autowired
    private CompressImgDao compressImgDao;
    @Autowired
    private LabelDao labelDao;
    @Autowired
    GetUserByTokenUtil getUserByTokenUtil;

    /**
     * 返回所有标签对象
     */
    @Override
    public ResponseResult findAll(HttpServletResponse resp) throws Exception {

        Publish publish = null;
        /**
         将标签对象存入Publish中
         */
        try {
            publish = new Publish();

            publish.setProductCategories(categoriesDao.findAll());
            publish.setCampuses(campusDao.findAll());

            if (publish.getCampuses() != null) {
                if (publish.getProductCategories() != null) {
                    return ResponseResult.build(resp, 200, 30010, "成功查询标签和分类数据", publish);

                } else {
                    return ResponseResult.build(resp, 500, 30012, "发布的商品缺少分类数据", publish);
                }
            } else {
                return ResponseResult.build(resp, 500, 30011, "发布的商品缺少标签数据", publish);
            }


        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.build(resp, 500, -1, "PublishServiceImpl.findAll方法内部异常", publish);
        }


    }

    @Override

    /**
     * 发布信息保存到数据库
     */
    public ResponseResult save(HttpServletRequest request, HttpServletResponse resp, JSONObject jsonPram) throws Exception {
        Product product = null;
        ProductAndCampus productAndCampus = null;
        //从json获取分类数组
        JSONArray categoriesIdArray = null;
        Integer categoriesId = null;
        //从json获取imgsUrl数组
        JSONArray imgsArray = null;
        //从json获取缩略图数组
        JSONArray compressArray = null;
        //从json获取campusArry数组
        JSONArray campusArray = null;
        Integer campusId = null;
        int isNew;
        int isNegotiable;

        try {
            productAndCampus = new ProductAndCampus();
            //从json获取分类数组
            try{
                categoriesIdArray = jsonPram.getJSONArray("categoriesId");
            }catch (ClassCastException e)
            {
                try{
//                    e.printStackTrace();
                    /**如果传过来的分类只有一个就用Int*/
                    categoriesId = jsonPram.getIntValue("categoriesId");
                }catch (ClassCastException e1)
                {
                    /**如果还不符合预期的分类类型就报错*/
                    e1.printStackTrace();
                    return ResponseResult.build(resp,500,30012,"分类数据不符合规范",null);
                }

            }
            //从json获取imgsUrl数组
            imgsArray = jsonPram.getJSONArray("productImgsUrl");
            //从json获取compressImgsUrl数组
            compressArray = jsonPram.getJSONArray("compressImgsUrl");
//            System.out.println(compressArray);
            /**试图从json获取campusArry数组*/
            try{
                campusArray = jsonPram.getJSONArray("campusId");
                if(campusArray==null||campusArray.size()==0){
                    return ResponseResult.fail(resp,"球球你选一个校区吧  ┭┮﹏┭┮");
                }
            }catch (ClassCastException e)
            {
                try
                {
                    /**如果传过来的校区只有一个就用Int*/
                    campusId = jsonPram.getIntValue("campusId");
                }
                catch(ClassCastException e1)
                {
                    /**如果还不符合预期的校区类型就报错*/
                    e1.printStackTrace();
                    return ResponseResult.build(resp,500,30012,"校区数据不符合规范",null);
                }
            }

            JSONObject label = jsonPram.getJSONObject("productLabels");
            isNew = label.getIntValue("isNew");
            isNegotiable = label.getIntValue("isNegotiable");

            /**
             保存product数据到数据库
             //         */
            try {
                product = jsonPram.getObject("product", Product.class);
//                product.setUserId(getUserByTokenUtil.getUser(request, resp).getUserId()); //得到userId并存入product中
                if (product.getProductPrice() < 0 || product.getPurchasePrice() < 0) {
                    return ResponseResult.build(resp, 500, 30013, "商品价格不符合规范", product);
                }
                productDao.saveProduct(product);

            } catch (JSONException e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseResult.build(resp, 500, 30014, "数据类型输入错误", product);
            }

            int productId = product.getProductId();

            /**
             保存product和校区关系到数据库
             */
            /**判断传过来的校区是单数还是复数*/
            if(campusId != null)
            {
                productAndCampus.setCampusId(campusId);
                productAndCampus.setProductId(product.getProductId());
                productAndCampusDao.save(productAndCampus);
            }else {
            for (int i = 0; i < campusArray.size(); i++) {
                    productAndCampus.setCampusId(campusArray.getIntValue(i));
                    productAndCampus.setProductId(product.getProductId());
                    productAndCampusDao.save(productAndCampus);
                }
            }
            /**
             保存product和分类关系到数据库
             */
            /**判断传过来的分类是单数还是复数*/
            if(categoriesId != null)
            {
                productAndCategoriesDao.save(productId,categoriesId);
            }else {
                for (int i = 0; i < categoriesIdArray.size(); i++) {
                    productAndCategoriesDao.save(productId, categoriesIdArray.getIntValue(i));
                }
            }

            /**
             保存imgsUrl到数据库 并与product的关系到数据库
             */
            for (int i = 0; i < imgsArray.size(); i++) {
                productImgDao.save(productId, imgsArray.getString(i));
            }
            /**
             保存compressImg到数据库 并与product的关系到数据库
             */
            for (int i = 0; i < imgsArray.size(); i++) {
                compressImgDao.save(productId,compressArray.getString(i));
            }

            /**
             保存productLabels与product的关系到数据库
             */
            labelDao.save(productId, isNew, isNegotiable);
            product = productDao.findProductById(productId);
            return ResponseResult.build(resp, 200, 30000, "发布商品成功", product);

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            return ResponseResult.build(resp, 500, 30001, "商品发布状态：发布失败,PublishServiceImpl.save方法内部异常", null);
        }


    }

    @Override
    public ResponseResult update(HttpServletRequest request, HttpServletResponse resp, JSONObject jsonPram) throws Exception
    {
        Product product = null;
        ProductAndCampus productAndCampus = null;
        //从json获取分类数组
        JSONArray categoriesIdArray = null;
        Integer categoriesId = null;
        //从json获取imgsUrl数组
        JSONArray imgsArray = null;
        //从json获取缩略图数组
        JSONArray compressArray = null;
        //从json获取campusArry数组
        JSONArray campusArray = null;
        Integer campusId = null;
        int isNew;
        int isNegotiable;

        try {
            productAndCampus = new ProductAndCampus();
            //从json获取分类数组
            try{
                categoriesIdArray = jsonPram.getJSONArray("categoriesId");
            }catch (ClassCastException e)
            {
                try{
//                    e.printStackTrace();
                    /**如果传过来的分类只有一个就用Int*/
                    categoriesId = jsonPram.getIntValue("categoriesId");
                }catch (ClassCastException e1)
                {
                    /**如果还不符合预期的分类类型就报错*/
//                    e1.printStackTrace();
                    return ResponseResult.build(resp,500,30028,"分类数据不符合规范",null);
                }

            }
            //从json获取imgsUrl数组
            imgsArray = jsonPram.getJSONArray("productImgsUrl");
            //从json获取compressImgsUrl数组
            compressArray = jsonPram.getJSONArray("compressImgsUrl");
//            System.out.println(compressArray);
            /**试图从json获取campusArry数组*/
            try{
                campusArray = jsonPram.getJSONArray("campusId");

            }catch (ClassCastException e)
            {
                try
                {
//                    e.printStackTrace();
                    /**如果传过来的校区只有一个就用Int*/
                    campusId = jsonPram.getIntValue("campusId");
                }
                catch(ClassCastException e1)
                {
                    /**如果还不符合预期的校区类型就报错*/
//                    e1.printStackTrace();
                    return ResponseResult.build(resp,500,30027,"校区数据不符合规范",null);
                }
            }

            JSONObject label = jsonPram.getJSONObject("productLabels");
            isNew = label.getIntValue("isNew");
            isNegotiable = label.getIntValue("isNegotiable");

            /**
             保存product数据到数据库
             //         */
            try {
                product = jsonPram.getObject("product", Product.class);
//                product.setUserId(getUserByTokenUtil.getUser(request, resp).getUserId()); //得到userId并存入product中
                if (product.getProductPrice() < 0 || product.getPurchasePrice() < 0)
                {
                    return ResponseResult.build(resp, 500, 30029, "商品价格不符合规范", product);
                }
                productDao.updateProduct(product);

            } catch (JSONException e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseResult.build(resp, 500, 30014, "数据类型输入错误", product);
            }

            int productId = product.getProductId();

            /**
             * 更新product和校区关系到数据库
             * 清除原有关系->重新插入新关系
             */
            /**清除原有关系*/
            productAndCampusDao.clean(productId);
            /**判断传过来的校区是单数还是复数*/
            if(campusId != null)
            {
                productAndCampus.setCampusId(campusId);
                productAndCampus.setProductId(product.getProductId());
                productAndCampusDao.save(productAndCampus);
            }else {
                for (int i = 0; i < campusArray.size(); i++) {
                    productAndCampus.setCampusId(campusArray.getIntValue(i));
                    productAndCampus.setProductId(product.getProductId());
                    productAndCampusDao.save(productAndCampus);
                }
            }
            /**
             * 更新product和分类关系到数据库
             * 清除原有关系->重新插入新关系
             */
            /**判断传过来的分类是单数还是复数*/
            /**清除原有关系*/
            productAndCategoriesDao.clean(productId);
            if(categoriesId != null)
            {
                productAndCategoriesDao.save(productId,categoriesId);
            }else {
                for (int i = 0; i < categoriesIdArray.size(); i++) {
                    productAndCategoriesDao.save(productId, categoriesIdArray.getIntValue(i));
                }
            }

            /**
             * 保存imgsUrl到数据库 并与product的关系到数据库
             * 清除原有图片url->重新插入新图片url
             */
            /**清除原有图片*/
            productImgDao.clean(productId);
            for (int i = 0; i < imgsArray.size(); i++) {
                productImgDao.save(productId, imgsArray.getString(i));
            }
            /**
             * 更新compressImg到数据库 并与product的关系到数据库
             * 清除原有图片url->重新插入新图片url
             */
            /**清除原有图片*/
            compressImgDao.clean(productId);
            for (int i = 0; i < imgsArray.size(); i++) {
                compressImgDao.save(productId,compressArray.getString(i));
            }

            /**
             保存productLabels与product的关系到数据库
             */
            /**清除原有标签*/
            labelDao.clean(productId);
            labelDao.save(productId, isNew, isNegotiable);
            product = productDao.findProductById(productId);
            return ResponseResult.build(resp, 200, 30025, "修改商品成功", product);

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.build(resp, 500, 30026, "修改商品失败,PublishServiceImpl.save方法内部异常", null);
        }
    }


}
